<template>
	<div class="foSi14 poRel" style="padding: 20px;">
		<div class="borRad20 coFFF hei34 dis disAl cuPo poAbs fanhui bac6b7" @click.stop="fanhui()">返回</div>
		<div style="height: 30px;"></div>
		<div class="mar" style="width: 840px;">
			<div class="foSi12 titl">基本信息</div>
			<el-form ref="ruleForm" :model="ruleForm" :rules="rules">
				<div class="wid100 hei44 dis disAl item-l mar-bott10">
					<div class="dis disAl disJuB hei100 item-r" style="border-right: 2px solid #fff;">
						<div>类型</div>
						<div v-if="type === 1">团课</div>
						<div v-if="type === 2">精品课</div>
						<div v-if="type === 3">私教课</div>
					</div>
					<div v-if="type === 3" class="dis disAl disJuB hei100 item-r">
						<div class="dis disAl">
							<span class="mar-right5" style="color: #FF0000;">*</span>
							<span>老师课时费（元/节）</span>
						</div>
						<el-form-item class="mp0" prop="classFee">
							<el-input v-model="ruleForm.classFee" style="width: 140px;" placeholder="请输入老师课时费" />
						</el-form-item>
					</div>
					<div v-if="type !== 3" class="dis disAl disJuB hei100 item-r">
						<div class="dis disAl">
							<span class="mar-right5" style="color: #FF0000;">*</span>
							<span>容纳人数（人）</span>
						</div>
						<el-form-item class="mp0" prop="galleryful">
							<el-input v-model="ruleForm.galleryful" style="width: 140px;" placeholder="请填写人数" />
						</el-form-item>
					</div>
				</div>
				<div class="wid100 hei44 dis disAl item-l mar-bott10">
					<div class="dis disAl disJuB hei100 item-r">
						<div class="dis disAl">
							<span class="mar-right5" style="color: #FF0000;">*</span>
							<span>课程名称</span>
						</div>
						<el-form-item class="mp0" prop="name">
							<el-input v-model="ruleForm.name" style="width: 140px;" placeholder="请填写课程名称" />
						</el-form-item>
					</div>
					<div>1-30个字符，支持汉字，字母及数字。</div>
				</div>
				<div class="wid100 hei44 dis disAl item-l mar-bott10">
					<div class="dis disAl disJuB hei100 item-r" style="border-right: 2px solid #fff;">
						<div class="dis disAl">
							<span class="mar-right5" style="color: #FF0000;">*</span>
							<span>课程时长（分钟）</span>
						</div>
						<el-form-item class="mp0" prop="kcTime">
							<el-input v-model="ruleForm.kcTime" style="width: 140px;" placeholder="请输入课程时长" />
						</el-form-item>
					</div>
					<div class="dis disAl disJuB hei100 item-r">
						<div class="dis disAl">颜色</div>
						<el-popover v-model="isPopover" popper-class=".monitor-yt-popover1" placement="bottom"
							width="220" trigger="click">
							<div class="wid100">
								<div class="coFFF dis disAl"
									style="background: #84878d;height: 24px;padding-left: 10px;">选颜色</div>
								<div class="wid100 dis disAl flwa" style="padding: 11px 5px 5px 11px;">
									<div v-for="(item,index) in colorList" :key="index"
										@click.stop="ruleForm.color = item,isPopover = false" class="col cuPo"
										:style="'background: #'+item+';'">
									</div>
								</div>
							</div>
							<div slot="reference" class="dis disAl hei34 bacFFF cuPo"
								style="border: 1px solid #d9d9d9;">
								<span style="width: 10px;"></span>
								<span style="width: 100px;height: 20px;"
									:style="'background: #'+ruleForm.color+';'"></span>
								<div class="dis disJuC" style="width: 40px;">
									<i class="el-icon-arrow-down"></i>
								</div>
							</div>
						</el-popover>
					</div>
				</div>
				<div class="wid100 hei44 dis disAl item-l mar-bott10">
					<div class="dis disAl disJuB hei100 item-r" style="border-right: 2px solid #fff;">
						<div class="dis disAl">
							<span class="mar-right5" style="color: #FF0000;">*</span>
							<span>老师</span>
						</div>
						<el-form-item class="mp0" prop="teacherName">
							<el-select v-model="ruleForm.teacherName" style="width: 140px" placeholder="请选择">
								<el-option v-for="(item,index) in teacherList" :key="index" :label="item.name"
									:value="item.id" />
							</el-select>
						</el-form-item>

					</div>
					<div class="dis disAl disJuB hei100 item-r">
						<div class="dis disAl">课程难度</div>
						<div class="dis disAl">
							<svg-icon v-for="(item,index) in 5" :key="index"
								@click.stop="ruleForm.difficulty = (index+1)"
								:icon-class="index+1 <= Number(ruleForm.difficulty)?'s_xing':'k_xing'" class="mar0 cuPo"
								style="width: 20px;height: 20px;fill: #f49352;" />
						</div>
					</div>
				</div>
				<div class="wid100 dis disAl item-l mar-bott10" style="height: 100px;">
					<div class="dis disJuB item-r" style="padding: 5px 15px;">
						<div class="dis" style="padding-top: 10px;">
							<span class="mar-right5" style="color: #FF0000;">*</span>
							<span>课程展示封面图</span>
						</div>
						<div style="width: 160px;height: 74px;">
							<el-image :src="ruleForm.image" fit="fill" class="wh100"></el-image>
						</div>
					</div>
					<div class="dis disAl item-r">
						<div class="borRad20 coFFF dis disAl hei34 cuPo" @click.stop="shuaVisible = true"
							style="background: #6b7cdd;padding: 0 10px;">
							选择图片</div>
						<span class="mar-left20 foSi12" style="color: #b8b8b8;">（建议尺寸750*422像素）</span>
					</div>
				</div>
				<div class="wid100 hei44 dis disAl item-l mar-bott10">
					<div class="dis disAl disJuB hei100 item-r">
						<div class="dis disAl">课程序号</div>
						<div class="dis disAl">
							<div class="dis disAl cuPo" @click.stop="ruleForm.serial = 1">
								<div class="dis disAl disJuC bacFFF borRad50"
									style="width: 14px;height: 14px;border: 1px solid #6b7cdd;">
									<div v-if="ruleForm.serial === 1" class="borRad50"
										style="width: 6px;height: 6px;background: #6b7cdd;"></div>
								</div>
								<div class="mar-left5">置顶</div>
							</div>
							<div class="dis disAl cuPo mar-left10" @click.stop="ruleForm.serial = 2">
								<div class="dis disAl disJuC bacFFF borRad50"
									style="width: 14px;height: 14px;border: 1px solid #6b7cdd;">
									<div v-if="ruleForm.serial === 2" class="borRad50"
										style="width: 6px;height: 6px;background: #6b7cdd;"></div>
								</div>
								<div class="mar-left5">自定义</div>
							</div>
						</div>
					</div>
					<div v-if="ruleForm.serial === 2" class="dis disAl disJuB hei100 item-r">
						<el-form-item class="mp0" prop="serialNumber">
							<el-input v-model="ruleForm.serialNumber" style="width: 310px;"
								placeholder="请输入数字，数值越大越靠前展示" />
						</el-form-item>
					</div>
				</div>
				<div class="wid100 dis item-l mar-bott10" style="padding: 5px 15px;">
					<div class="dis mar-right20" style="padding-top: 10px;">简介</div>
					<div class="class-desc">
						<el-upload action="#" :http-request="handleAvatarSuccess1" :before-upload="beforeAvatarUpload">
							<div class="rich-insert	">
								<svg-icon icon-class="up-editior" class="mar0 cuPo" style="width: 25px;height: 25px;" />
								<span class="mar-left10">插入图片</span>
							</div>
						</el-upload>
						<div id="richId" class="rich-row" contenteditable="true" @click="handleSelection"
							@input="handleSelection" />
					</div>
				</div>
			</el-form>
		</div>
		<div class="dis disAl disJuC " style="padding: 30px 0;">
			<div class="dis disAl hei34 borRad20 coFFF cuPo bac6b7" style="padding: 0 24px;"
				@click.stop="submitForm('ruleForm')">保存</div>
			<div class="mar-left30 dis disAl hei34 borRad20 coFFF cuPo" style="background: #616b74;padding: 0 24px;"
				@click.stop="fanhui()">取消</div>
		</div>
		<div v-if="shuaVisible" class="zhezhao wh100"></div>
		<div v-if="shuaVisible" class="zhezhaoN dis disAl disJuC wh100">
			<div class="poRel borRad10 bacFFF" style="width: 650px;">
				<div class="poRel" style="padding: 30px;">
					<svg-icon icon-class="guanbi" class="mar0 cuPo poAbs" @click.stop="shuaVisible = false"
						style="color: #ACACAC;width: 24px;height: 24px;top: 5px;right: 5px;" />
					<div class="wid100 poRel" style="height: 350px;overflow: hidden;">
						<div class="avatar-tips">操作提示：鼠标滚轮缩放大小，拖动选区进行区域选择</div>
						<vue-cropper class="wh100" ref="cropper" :img="image" :canMove="false" :autoCropWidth="225"
							:autoCropHeight="126" :outputSize="0.6" :outputType="outputType" :autoCrop="true"
							:fixed="true" :fixedNumber="[225,126]" :original="false" :centerBox="true" :infoTrue="true"
							fillColor="#ffffff" mode="contain"></vue-cropper>
					</div>
					<div class="wid100 dis disAl disJuC foSi14 coFFF" style="padding: 20px 0;">
						<el-upload action="#" :http-request="handleAvatarSuccess2" :before-upload="beforeAvatarUpload">
							<div class="mar-right20 que cuPo" style="background: #f49352;">上传新图</div>
						</el-upload>

						<div class="mar-right20 que cuPo bac6b7" @click.stop="jietu">确认</div>
						<div class="que cuPo" style="background: #616b74;" @click.stop="shuaVisible = false">取消</div>
					</div>
				</div>
			</div>
		</div>
	</div>
</template>

<script>
	import {
		getXuan
	} from '@/utils/limits.js'
	import {
		mapGetters
	} from 'vuex'
	import {
		getVenue
	} from '@/api/venue'
	import {
		uploadimg
	} from '@/api/utils'
	import {
		VueCropper
	} from 'vue-cropper'
	import {
		courseDetails,
		courseAddEdit
	} from '@/api/coures'
	export default {
		name: 'courseEdit1',
		components: {
			VueCropper
		},
		data() {
			const validateGalleryful = (rule, value, callback) => {
				var reg = new RegExp('^-?[0-9]*.?[0-9]*$')
				if (!reg.test(value) || !value || value > 10000 || value === 0) {
					callback(new Error('请填写数值(1~10000)'))
				} else {
					callback()
				}
			}
			const validateTime = (rule, value, callback) => {
				var reg = new RegExp('^-?[0-9]*.?[0-9]*$')
				if (!reg.test(value) || !value || value > 1440 || value === 0) {
					callback(new Error('请输入课程时长(1~1440)'))
				} else {
					callback()
				}
			}
			const validateTeacher = (rule, value, callback) => {
				console.log(value)
				if (value === 0) {
					callback(new Error('请选择老师'))
				} else {
					callback()
				}
			}
			const validateSerial = (rule, value, callback) => {
				var reg = new RegExp('^-?[0-9]*.?[0-9]*$')
				if (this.ruleForm.serial === 2) {
					if (!reg.test(value) || !value || value === 0) {
						callback(new Error('请输入数字，数值越大越靠前'))
					} else {
						callback()
					}
				} else {
					callback()
				}
			}
			const validateClassFee = (rule, value, callback) => {
				var reg = new RegExp('^-?[0-9]*.?[0-9]*$')
				if (this.type === 3) {
					if (!reg.test(value) || (!value && value !== 0) || value > 9999.99 || value < 0) {
						callback(new Error('请输入0~9999.99内的数值'))
					} else {
						callback()
					}
				} else {
					callback()
				}
			}
			return {
				shuaVisible: false,
				isPopover: false,
				colorList: [
					"FBB0A1", "FEFF99", "BCFD84", "95E2F5", "928FD9",
					"47D95E", "E5D0C4", "9c4b4b", "db6a51", "f5c856",
					"75c090", "ed707a", "b0649a", "d19fc9", "8b9599",
					"9c8088", "a6c399", "5b6fc1", "9583b0", "b0a763",
					"da8e6d", "b07187", "F8F6EF", "EBDBC9", "DAE1EB",
					"EBF4F7", "E7DAD1", "F7F1F1", "F3D5D7", "DDCCCD",
					"F4F0E5", "EDA7A6", "D0CAB7", "EDE9E8", "E6CEB7",
					"F4D7B7", "F2E8D5", "FBF0C8", "ABB5C8", "DCDCDC",
					"FBECE6", "C4C6B8", "EADDE3", "ECF0EF"
				],
				teacherList: [],
				outputType: 'jpeg',
				image: 'https://www.jianyigongxiang.com/public/membercard/kcfm.jpg',
				cropW: 225,
				cropH: 126,
				ruleForm: {
					name: '',
					galleryful: '',
					kcTime: '',
					color: 'd19fc9',
					teacherName: '',
					difficulty: '',
					serial: 2,
					serialNumber: '',
					classFee: '',
					image: 'https://www.jianyigongxiang.com/public/membercard/kcfm.jpg'
				},
				rules: {
					name: [{
						required: true,
						message: '请填写1-30个字符课程名称',
						trigger: 'blur'
					}],
					galleryful: [{
						required: true,
						trigger: 'blur',
						validator: validateGalleryful
					}],
					kcTime: [{
						required: true,
						trigger: 'blur',
						validator: validateTime
					}],
					teacherName: [{
						required: true,
						trigger: 'change',
						validator: validateTeacher
					}],
					serialNumber: [{
						required: true,
						trigger: 'blur',
						validator: validateSerial
					}],
					classFee: [{
						required: true,
						trigger: 'blur',
						validator: validateClassFee
					}],
				},
				type: 1,
				url: '',
				cid: ''
			}
		},
		computed: {
			...mapGetters([
				'permission_routes',
				'roles'
			])
		},
		created() {
			var query = this.$route.query
			this.type = Number(query.type)
			this.cid = query.cid
			this.url = '/course/courseParticulars?type=' + query.type + '&cid=' + query.cid
			var xuanList = [{
				name: '编辑课程',
				url: '/course/courseEdit1?type=' + query.type + '&cid=' + query.cid,
				pd: true
			}]
			var xuanList1 = getXuan(xuanList, this.roles)
			this.$store.dispatch('user/changeXuan', {
				key: 'xuanList',
				value: xuanList1
			})
			this.$store.dispatch('user/changeXuan', {
				key: 'xuan',
				value: 0
			})
			this.getVen()
			this.getList()
		},
		methods: {
			getVen() {
				getVenue().then(response => {
					const {
						data
					} = response
					var activities = [{
						id: 0,
						name: '请选择'
					}]
					this.teacherList = activities.concat(data)
				}).catch(error => {
					console.log(error)
				})
			},
			fanhui() {
				this.$router.go(-1)
			},
			handleTag() {
				const parseDom = this.parseDom(`<img src="${this.imageUrl}">`)
				// 在光标处插入dom
				this.range.insertNode(parseDom)
				// 光标开始和光标结束重叠
				this.range.collapse(true)
			},
			// 记录光标位置等 （debounce防抖提升性能）
			handleSelection(e) {
				this.selection = getSelection()
				// 光标对象
				this.range = this.selection.getRangeAt(0)
				// 获取光标对象的范围界定对象
				this.textNode = this.range.startContainer
				// 获取光标位置
				this.rangeStartOffset = this.range.startOffset
				this.ruleForm.brief = e.target.innerHThtmML
			},
			// 转dom对象
			parseDom(arg) {
				var objE = document.createElement('div')
				objE.innerHTML = arg
				return objE.childNodes[0]
			},
			handleAvatarSuccess1(file) {
				var that = this
				let mf = new FormData()
				mf.append('file', file.file)
				uploadimg(mf).then(response => {
					that.imageUrl = response.data
					that.handleTag()
				})
			},
			beforeAvatarUpload(file) {
				const isJPG = file.type === 'image/jpeg' || file.type === 'image/png'
				const isLt2M = file.size / 1024 / 1024 < 5
				if (!isJPG) {
					this.$message.error('上传头像图片只能是 JPG或PNG 格式!')
				}
				if (!isLt2M) {
					this.$message.error('上传头像图片大小不能超过 5MB!')
				}
				return isJPG && isLt2M
			},
			jietu() {
				var that = this
				this.$refs.cropper.getCropData(data => {
					var file = this.dataURLtoBlob(data, 'chaijian')
					let mf = new FormData()
					mf.append('file', file)
					uploadimg(mf).then(response => {
						that.ruleForm.image = response.data
						that.shuaVisible = false
					})
				})
			},
			dataURLtoBlob(dataurl, name) {
				var arr = dataurl.split(","),
					mime = arr[0].match(/:(.*?);/)[1],
					bstr = atob(arr[1]),
					n = bstr.length,
					u8arr = new Uint8Array(n);
				while (n--) {
					u8arr[n] = bstr.charCodeAt(n);
				}
				return new File([u8arr], name, {
					type: mime
				});
			},
			handleAvatarSuccess2(file) {
				this.image = URL.createObjectURL(file.file)
			},
			beforeAvatarUpload2(file) {
				const isJPG = file.type === 'image/jpeg' || file.type === 'image/png'
				this.outputType = file.type === 'image/jpeg' ? 'jpeg' : file.type === 'image/png' ? 'png' : ''
				const isLt2M = file.size / 1024 / 1024 < 5
				if (!isJPG) {
					this.$message.error('上传头像图片只能是 JPG或PNG 格式!')
				}
				if (!isLt2M) {
					this.$message.error('上传头像图片大小不能超过 5MB!')
				}
				return isJPG && isLt2M
			},
			submitForm(formName) {
				this.$refs[formName].validate((valid) => {
					if (valid) {
						courseAddEdit({
							'id': this.cid,
							'name': this.ruleForm.name,
							'type': this.type,
							'hour_subsidy': this.ruleForm.classFee,
							'people_num': this.ruleForm.galleryful,
							'long_time': this.ruleForm.kcTime,
							'colors': this.ruleForm.color,
							'coach_id': this.ruleForm.teacherName,
							'dif_star': this.ruleForm.difficulty,
							'cover_img': this.ruleForm.image,
							'sort': this.ruleForm.serialNumber,
							'brief': this.ruleForm.brief
						}).then(response => {
							this.fanhui()
						}).catch(error => {
							console.log(error)
						})
					} else {
						this.$message.error('请按规则填写完整信息')
						return false
					}
				})
			},
			getList() {
				courseDetails({
					'courseid': this.cid // 1团课2精品课3私教课4班课
				}).then(response => {
					const {
						data
					} = response
					this.ruleForm = {
						name: data.name,
						galleryful: data.people_num,
						kcTime: data.long_time,
						color: data.colors,
						teacherName: data.coach_id,
						difficulty: data.dif_star,
						serial: data.sort ? 2 : 1,
						serialNumber: data.sort,
						classFee: data.hour_subsidy,
						image: data.cover_img,
						brief: data.brief
					}
					var divID = document.getElementById("richId");
					divID.innerHTML = data.brief
				}).catch(error => {
					console.log(error)
				})
			}
		}
	}
</script>

<style>
	.monitor-yt-popover1 {
		padding: 0;
		border-color: #84878d;
	}

	.monitor-yt-popover1 .popper__arrow::after {
		border-bottom-color: #84878d !important;
	}
</style>

<style lang="scss" scoped>
	.fanhui {
		background: #6b7cdd;
		padding: 0 24px;
		right: 63px;
		top: 10px;
		z-index: 10;
	}

	.m-action-step1 {
		width: 460px;
		height: 65px;
		margin: 0 auto 36px;
	}

	.m-action-step2 {
		width: 248px;
	}

	.curr1 {
		width: 36px;
		height: 36px;
		border-radius: 50%;
		background: #e8e8e8;
		text-align: center;
		line-height: 36px;
		font-weight: 700;
		color: #a7a7a7;
	}

	.curr2 {
		background: #6b7cdd;
		color: #fff;
	}

	.titl {
		height: 25px;
		color: #787878;
	}

	.field {
		padding: 5px 15px;
		margin-bottom: 8px;
		background: #f2f2f2;
	}

	.label {
		float: left;
		width: 135px;
		min-height: 32px;
		line-height: 32px;
		padding-right: 10px;
		white-space: nowrap;
	}

	.item-l {
		background: #f2f2f2;
	}

	.item-r {
		width: 420px;
		padding: 0 15px;
	}

	.col {
		width: 36px;
		height: 36px;
		margin: 0 4px 3px 0;
	}

	.class-desc {
		width: 721px;
		height: 230px;
		border: 1px solid #d9d9d9;
		padding: 5px;
		line-height: 1.5;
	}

	.rich-insert {
		width: 100%;
		height: 30px;
		padding: 2px 5px;
		position: relative;
		vertical-align: text-top;
		box-sizing: border-box;
		overflow: hidden;
		display: flex;
		align-items: center;
	}

	.rich-row {
		width: 100%;
		height: calc(100% - 31px);
		border: 0;
		background-color: #fff;
		box-sizing: border-box;
		padding: 5px;
		margin-top: 1px;
		outline: 0;
		overflow-y: scroll;
		overflow-x: hidden;
	}

	::v-deep .el-upload:focus {
		color: #000 !important;
	}

	::v-deep .el-upload-list {
		display: none;
	}

	::v-deep .el-checkbox__input.is-checked .el-checkbox__inner {
		background-color: #6b7cdd;
		border-color: #6b7cdd;
	}

	::v-deep .el-checkbox__input.is-focus .el-checkbox__inner {
		border-color: #6b7cdd;
	}

	::v-deep .el-checkbox__label {
		color: #000 !important;
	}

	.avatar-tips {
		position: absolute;
		bottom: 3px;
		left: 5px;
		z-index: 10;
		color: #fff;
		font-size: 12px;
	}

	.que {
		display: inline-block;
		padding: 0 24px;
		height: 34px;
		line-height: 34px;
		text-align: center;
		vertical-align: top;
	}
</style>
